// index/index.js
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
const app = new getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: null, //存储用户信息
    stripe:false,//是否为全面屏
    height: "0px", //页面高度
    active: 0, //底部标签栏
    display: false,
    productList: null, //商品信息
    max: 100, //购买数量最大值
    normInde: -1, //选择的子商品ID
    value: "",//搜索的值
    search: true, //是否显示搜索按钮
    values: false,//是否显示搜索按钮
    cartList: {}, //购物车集合
    cartPrice: 0, //购物车选中后的价格
    onCheckbox: [], //购物车选中的物品ID集合
    onChecked: [],//购物车手动选中的ID
    selectAll: false, //是否全选
    loadMore: true, //是否加载
    page_num:1,//主页页数
    searchb:true,//下拉时，真为全部商品获取，假为搜索商品获取
    divider:true,//最底部的横线，当为假的时候显示没有更多了
    class:"",//设定class
    indexLoad:true,//判断是否加载
  },
  //搜索获得聚焦时
  ju() {
    this.setData({
      search: true,
    })
  },
  //搜索框失去聚焦时
  shi() {
    if (this.data.value != null && this.data.values) {
      this.setData({
        search: false,
      })
    }
  },
  //返回按钮
  fanhui() {
    var that = this;
    wx.request({
      url: app.globalData.url + 'getProductNorm',
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        that.setData({
          productList: res.data.product,
          value: "",
          values: false,
          search: true,
          page_num:1,
          searchb:true,
          divider:true,
        })
      },
      fail(res) {
        wx.showToast({
          title: '服务器错误！',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  //搜索
  search(e) {
    var value = this.data.value;
    if (value == "") {
      return;
    }
    var that = this;
    if (this.data.value != null) {
      this.setData({
        search: false,
        values: true,
        divider:true,
      })
    }
    wx.request({
      url: app.globalData.url + 'searchProduct?search=' + value,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        var product = null;
        if (res.data.product != "") {
          product = res.data.product;
        }
        that.setData({
          page_num:1,
          productList: product,
          searchb:false,
        })
      },
      fail(res) {
        wx.showToast({
          title: '服务器错误！',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  //搜索框发生变化
  searchs(e) {
    this.setData({
      value: e.detail
    })
  },
  //删除购物车其中商品
  deleteCart(e){
    var cartId = e.target.dataset.src;
    var that = this;
    Dialog.confirm({
      title: '删除商品',
      message: '是否删除商品',
    }).then(() => {
      that.cartNumber({
        detail:0,
        target:{
          dataset:{
            src:cartId,
          }
        }
      });
    }).catch(() => {
      // on cancel
    });
    
  },

  //购物车读取
  cart() {
    if (app.globalData.userInfo == null) {
      wx.redirectTo({
        url: '../login/login?active=1',
      })
      wx.hideHomeButton();
      return;
    }
    var that = this;
    wx.request({
      url: app.globalData.url + 'getCart?user_id=' + this.data.userInfo.id + "&openId=" + that.data.userInfo.openId,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        var cart = null;
        var cartPrice = 0;
        var onChecked = new Array();
        if (res.data.cart != null) {
          cart = res.data.cart;
          var x = 0;
          cart.forEach(e => {
            onChecked[x] = e.id.toString();
            x++;
            that.data.onCheckbox.forEach(box => {
              if (e.id == box) {
                cartPrice += e.price * e.product_num;
              }
            })
          });
        }else{
          wx.showToast({
            title: '读取失败！',
            icon: 'error',
            duration: 2000
          })
        }
        that.setData({
          cartList: cart,
          cartPrice: cartPrice,
          onChecked: onChecked,
        })
        if (that.data.onChecked.length == that.data.onCheckbox.length) {
          that.setData({
            selectAll: true,
          })
        }else{
          that.setData({
            selectAll: false,
          })
        }
      },
      fail(res) {
        wx.showToast({
          title: '服务器错误！',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  //显示商品详情页面
  close(e) {
    app.globalData.price = e.currentTarget.dataset.src;
    wx.navigateTo({
      url: '../goods/goods',
    })
  },
  //设置标签栏主页
  onChange(e) {
    if (e.detail == 1) {
      this.cart(); //联网读取购物车
    }
    if (e.detail == 2) {
      if (app.globalData.userInfo == null) {
        wx.redirectTo({
          url: '../login/login?active=2',
        })
        wx.hideHomeButton();
        return;
      }
    }
    this.setData({
      active: e.detail,
      class:"",
    })
  },

  //购物车设置选中或者未选中
  onCheckbox(e) {
    var src = e.target.dataset.src;
    var cartPrice = this.data.cartPrice;
    var onCheckbox = this.data.onCheckbox.length + 1;
    var boom = false;
    if (onCheckbox == e.detail.length) {
      this.setData({
        cartPrice: cartPrice + src,
      })
    } else {
      this.setData({
        cartPrice: cartPrice - src,
      })
    }
    this.setData({
      onCheckbox: e.detail,
    })
    if (this.data.onChecked.length == this.data.onCheckbox.length) {
      boom = true;
    }
    this.setData({
      selectAll: boom,
    })
  },
  //全选商品
  selectAll(e) {
    if (!e.detail) {
      this.setData({
        onCheckbox: [],
        selectAll: false,
      })
    } else {
      this.setData({
        onCheckbox: this.data.onChecked,
        selectAll: true,
      })
    }
    this.cart();
  },
  //提交订单
  onSubmit(e) {
    var that = this.data;
    var userInfo = this.data.userInfo;
    wx.request({
      url: app.globalData.url + "setOrder?user_id=" + userInfo.id + "&cart_ids=" + that.onCheckbox + "&openId=" + userInfo.openId,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        var data = res.data;
        if (data.state == 1) {
          wx.navigateTo({
            url: '../buy/buy?' + "number=" + that.number + "&normId=" + that.onCheckbox,
          })
          return;
        } else if (data.state == 0) {
          console.log("服务器错误");
        } else if (data.state == -1) {
          console.log("购物车错误，请重新打开购物车");
        }
      }
    })
  },
  cartNumber(e) {
    //获取购物车商品的ID
    var cartId = e.target.dataset.src;
    //获取修改后的购物车商品数量
    var number = e.detail;
    var that = this;
    wx.request({
      url: app.globalData.url + "setCartNumber?id=" + cartId + "&product_num=" + number+"&user_id="+that.data.userInfo.id+"&openId="+that.data.userInfo.openId,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        if (res.data.state == 0) {
          Dialog.alert({
            message: '修改失败，点击确实刷新购物车',
          }).then(() => {
            // on close
            that.cart();
          });
        } else {
          that.cart();
        }
      },
      fail(res) {
        wx.showToast({
          title: '服务器错误！',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },

 //快速登录
  wxLogin(){
    if(app.globalData.userInfo!=null){
      this.deploy();
      return;
    }
    var that =this;
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        wx.request({
          url: app.globalData.url + 'getUserOpenId',
          method: "POST",
          data: {
            code: res.code
          },
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success(res) {
            //已注册，成功登录
            if (res.data.state == 1 && res.data.user.address != null && res.data.user.address != "") {
              app.globalData.userInfo=res.data.user;
              that.deploy();
            }
          }
        })
      }
    })
  },
  //配置首次打开的信息
  deploy(){
    this.setData({
      userInfo: app.globalData.userInfo,
      active: 0
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.wxLogin();
    var active = options.active;
    // const res = wx.getSystemInfoSync();
    // console.log(res.safe-area-inset-bottom());
    if (options.norm != null) {
      this.setData({
        norm: {
          product_id: options.product_id,
          id: options.normId,
        },
        number: options.number,
      })
      if (options.norm == 1) {
        this.addCart();
      } else {
        this.buyNow();
      }
    }
    if (active != null) {
      if (active == 1) {
        this.cart();
      }
    }
    if (active == null) {
      active = 0;
    }
    this.setData({
      active: active,
      display: true,
    })
    if(options.cart!=null){
      this.cart();
      this.setData({
        active:1,
        class:'class'
      })
    }
  },
  //下拉到底后加载
  loadMore() {
    var that = this;
    if (that.data.loadMore) {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        loadingType: 'spinner',
      });
      that.setData({
        loadMore: false,
      })
      if(this.data.searchb){
        wx.request({
          url: app.globalData.url + 'getProductNorm?page_num='+(that.data.page_num+1),//获取当前+1页
          method: "POST",
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success(res) {
            if(res.data.product!=null){
              that.loadMore2(res);
            }
          },
          fail(res) {
            wx.showToast({
              title: '服务器错误！',
              icon: 'error',
              duration: 2000
            })
          }
        })
      }else{
        wx.request({
          url: app.globalData.url + 'searchProduct?search='+that.data.value+'page_num='+(that.data.page_num+1),//获取当前+1页
          method: "POST",
          header: {
            "content-type": "application/x-www-form-urlencoded"
          },
          success(res) {
            if(res.data.product!=null){
              that.loadMore2(res);
            }
          },
          fail(res) {
            wx.showToast({
              title: '服务器错误！',
              icon: 'error',
              duration: 2000
            })
          }
        })
      }

    }
  },
  //下拉刷新，用于判断是否是最后一页
  loadMore2(res){
    var that = this;
    setTimeout(function () {
      if(res.data.product.pages<that.data.page_num+1){
        that.setData({
          divider:false,
        })
      }else{
        that.setData({
          productList:{
            list:that.data.productList.list.concat(res.data.product.list)
          },
          page_num:that.data.page_num+1,
        })
      }
      Toast.clear();
      that.setData({
        loadMore: true,
      })
     }, 1000)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          height: res.windowHeight,
        })
      },
    })
    let screenHeight = wx.getSystemInfoSync().screenHeight
    let bottom = wx.getSystemInfoSync().safeArea.bottom
    if(screenHeight!==bottom){
      this.setData({
        height:this.data.height-30,
        stripe:true,
      })
    }
    var that = this;
    wx.request({
      url: app.globalData.url + 'getProductNorm',
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        that.setData({
          productList: res.data.product,
          indexLoad:false,
        })
      },
      fail(res) {
        wx.showToast({
          title: '服务器错误！',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})